<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    :error="error"
    error-text="加载失败，请稍后重试！"
    :immediate-check="false"
    @load="onLoad"
  >
    <comment-item
      v-for="(item, index) in list"
      :key="index"
      :title="item.content"
      @reply-click="$emit('reply-click', $event)"
      :comment="item"
    />
  </van-list>
</template>

<script>
import { getComments } from '@/api/comment'
import CommentItem from './comment-item'
export default {
  name: 'CommentList',
  components: {
    CommentItem
  },
  props: {
    source: {
      type: [Number, String, Object],
      required: true
    },
    list: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      // 自定义 prop 数据验证
      validator(value) {
        return ['a', 'c'].includes(value)
      },
      default: 'a'
    }
  },
  data() {
    return {
      // list: [],
      loading: false,
      finished: false,
      offset: null, // 获取下一页数据的标记
      limit: 10, // 获取显示每页的评论条数
      error: false
    }
  },
  computed: {},
  watch: {},
  created() {
    this.loading = true
    this.onLoad()
  },
  mounted() {},
  methods: {
    async onLoad() {
      try {
        // 1.请求获取数据
        const { data } = await getComments({
          type: this.type,
          source: this.source.toString(),
          offset: this.offset,
          limit: this.limit
        })
        // 2.将数据添加到列表中
        const { results } = data.data
        this.list.push(...results)
        // 将 tatalCount 传递给父组件
        this.$emit('onload-success', data.data)
        // 3.将 loading 设置为 false
        this.loading = false
        // 4.判断是否还有数据
        if (results.length) {
          //   如果有 更新获取下一页的数据页码
          this.offset = data.data.last_id
        } else {
          //   如果没有 将 finished 设置为结束
          this.finished = true
        }
      } catch (error) {
        // console.log(error)
        this.error = true
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="less"></style>
